//
//  FSSecViewController.m
//  WZSOA
//
//  Created by 刘沿 on 16/6/30.
//  Copyright © 2016年 刘沿. All rights reserved.
//

#import "FSSecViewController.h"
#import "GDataDefines.h"


@interface FSSecViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,assign) NSInteger currentPage;

@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UITableView *tab;

@property (nonatomic,strong) UIButton *lastbtn;

@property (nonatomic,strong) UIView *VIew;

@property (nonatomic,copy) NSString *dataString;

@property (nonatomic,assign) NSInteger index;


@end

@implementation FSSecViewController

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView *tab = [[UITableView alloc] init];
    self.index = 0;
    self.tab = tab;

    self.tab.delegate = self;
    
    self.tab.dataSource = self;
    
    [self.view addSubview:tab];
    
    [tab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).mas_offset(80);
        
        make.left.equalTo(self.view.mas_left).mas_offset(10);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-10);
        
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(-10);
    }];

    self.view.backgroundColor = [UIColor colorWithRed:188/255.0 green:193/255.0 blue:196/255.0 alpha:1];
    UIView *view = [[UIView alloc] init];
    
    self.VIew = view;
    
    [self.view addSubview:view];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).mas_offset(10);
        
        make.left.equalTo(self.view.mas_left).mas_offset(10);
        
        make.right.equalTo(self.view.mas_right).mas_offset(-10);
        
        make.height.equalTo(@60);
        
    }];
    
    view.backgroundColor = [UIColor colorWithRed:236/255.0 green:247/255.0 blue:250/255.0 alpha:1];
    __weak typeof (self) weakSelf = self;
    [self.tab addHeaderWithCallback:^{
        weakSelf.currentPage = 1;
        [weakSelf loaddata]; //加载网络数据
    }];
    [self.tab headerBeginRefreshing];
    
}

- (void)loaddata{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    self.dataString = dateString;
    
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];

    NSArray *array = @[@{@"unid":dateString},@{@"userId":userId}];
    
    [HttpTools requestWithURL:Kexchlogistics arrays:array method:KgetMeetDate success:^(id JSON) {
        
        NSDictionary *dict = JSON;
        
        if (self.index == 0) {
            
            [self setUp:dict];

        }
        
        [self.tab reloadData];
        [self.tab headerEndRefreshing];
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)setUp:(NSDictionary *)dict{

    self.index ++;
    
    NSArray *arr = @[@"Monday",@"TUESDAY",@"WEDNESDAY",@"THURSDAY",@"FRIDAY",@"SATURDAY",@"SUNDAY"];
    
    NSArray *arr2 = @[@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",@"周日"];
    
//    CGFloat ViewW = self.view.frame.size.width;
//    CGFloat w = 0;
    CGFloat h = 7;
    for (int i = 0; i < arr.count; i ++) {
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        
        btn.titleLabel.numberOfLines = 2;
        
        [btn setTitle:[NSString stringWithFormat:@"%@\n%@",arr2[i],dict[arr[i]]] forState:UIControlStateNormal];
        
        if ([dict[arr[i]] isEqualToString:self.dataString]) {
            
            btn.selected = YES;
            
            [self defaultbtn:btn];
            
            self.lastbtn = btn;

        }
        
        [btn addTarget:self action:@selector(btnClcik:) forControlEvents:UIControlEventTouchUpInside];
        
        CGFloat x = (self.VIew.frame.size.width - 80)/7;
        
        CGFloat x1 = x*i + (i + 1)* 10;
        
        btn.frame = CGRectMake(x1, h, x , 60);
        
        [self.VIew addSubview:btn];
    }

}

- (void)btnClcik:(UIButton *)btn{
    self.currentPage = 1;
    //第一次点击的时候上一个按钮是直属单位
    
    btn.selected = YES;
    
    self.lastbtn.selected = NO;
    
    if (self.lastbtn == btn) {
        
        self.lastbtn.selected = YES;
        
        return;
    }
    
    [self.dataArray removeAllObjects];
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];

    NSString *str = [btn.titleLabel.text substringFromIndex:3];
    
    NSArray *arr = @[@{@"userId":userId},@{@"sDate":str},@{@"page":[NSString stringWithFormat:@"%ld",self.currentPage]}];
    
    [HttpTools postWithURL:Kexchlogistics arrays:arr method:KtoselectMeetPage success:^(id JSON) {
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
     
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没最新会议安排哦"];
        }
        
        [self.tab reloadData];
        [self.tab footerEndRefreshing];
        self.currentPage++;

        self.lastbtn = btn;
        
    } failure:^(NSError *error) {
        
    }];

}

- (void)defaultbtn:(UIButton *)btn{

    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    
    NSString *str = [btn.titleLabel.text substringFromIndex:3];
    
    NSArray *arr = @[@{@"userId":userId},@{@"sDate":str},@{@"page":[NSString stringWithFormat:@"%ld",self.currentPage]}];
    
    [HttpTools postWithURL:Kexchlogistics arrays:arr method:KtoselectMeetPage success:^(id JSON) {
        
         self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        
        if (self.dataArray.count == 0) {
            [self.view makeToast:@"暂时还没最新会议安排哦"];
        }
        [self.tab reloadData];
        [self.tab footerEndRefreshing];
        self.currentPage++;
        
    } failure:^(NSError *error) {
        
    }];
    
}

//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            FSReceiveModel * model = [[FSReceiveModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSReceiveModel * model = self.dataArray[indexPath.row];
    CGFloat height = 0;
    CGFloat  titlesize  = [FSHightTool heightbyString:model.title font:14 minsWidth:60];
    
    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
    CGFloat dessize = [FSHightTool heightbyString:desstring font:13 minsWidth:60];;
    height = titlesize + dessize + 20;
    return  height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    FSNewReceiveCell * cell = [FSNewReceiveCell cellWithTableView:tableView];
    FSNewReceiveModel * model = self.dataArray[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FSNewReceiveModel * model = self.dataArray[indexPath.row];

    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    FSNewReceiveDetailController *neceD = [story instantiateViewControllerWithIdentifier:@"NewDetailReceiveVC"];

    neceD.type = meeting;
    
    neceD.unid = model.fileId;
    
    [self.navigationController pushViewController:neceD animated:YES];
    
}





@end










